package com.itheima.pinda.authority.controller.auth;

import com.itheima.pinda.authority.biz.service.auth.ValidateCodeService;
import com.itheima.pinda.authority.biz.service.auth.impl.AuthManager;
import com.itheima.pinda.authority.dto.auth.LoginDTO;
import com.itheima.pinda.authority.dto.auth.LoginParamDTO;
import com.itheima.pinda.base.BaseController;
import com.itheima.pinda.base.R;
import com.itheima.pinda.log.annotation.LoginLog;
import com.itheima.pinda.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录(认证) 控制器
 *
 * @author llhuang10
 * @date 2021/8/27 9:36
 */
@Slf4j
@RestController
@RequestMapping("/anno")
@Api(tags = "登录接口", value = "LoginController")
public class LoginController extends BaseController {


    @Resource
    private ValidateCodeService validateCodeService;

    @Resource
    private AuthManager authManager;


    /**
     * 为前端系统生成验证码
     * produces = "image/png"  回显的是图片
     *
     * @param key 前端系统随机生成的key
     * @param res response
     */
    @SysLog("生成验证码")
    @ApiOperation(value = "生成验证码", notes = "验证码")
    @GetMapping(value = "/captcha", produces = "image/png")
    public void captcha(@RequestParam("key") String key, HttpServletResponse res) {
        validateCodeService.create(key, res);
    }

    /**
     * 校验验证码
     *
     * @param loginParamDTO 封装的是前端登录传过来的参数, 账号/密码/验证码/验证码key [个人觉得这个应该为 VO, 不应该是DTO]
     * @return true 或 false
     */
    @PostMapping("/check")
    @ApiOperation(notes = "校验验证码", value = "校验验证码")
    public boolean check(@RequestBody LoginParamDTO loginParamDTO) {
        // 校验验证码是否正确
        return validateCodeService.check(loginParamDTO.getCode(), loginParamDTO.getKey());
    }

    /**
     * 登录认证
     *
     * @param loginParamDTO 封装的是前端登录传过来的参数, 账号/密码/验证码/验证码key [个人觉得这个应该为 VO, 不应该是DTO]
     * @return true 或 false
     */
    @LoginLog       // 这里把 @LoginLog 注释掉, 即可关闭自己写的登录日志记录功能, 使用的AOP切面技术
    @PostMapping("/login")
    @ApiOperation(notes = "登录认证", value = "登录认证")
    public R<LoginDTO> login(@Validated @RequestBody LoginParamDTO loginParamDTO) {
        // 校验验证码是否正确
        boolean check = validateCodeService.check(loginParamDTO.getCode(), loginParamDTO.getKey());
        if (check) {
            // 验证码校验通过, 执行具体的登录认证逻辑
            R<LoginDTO> r = authManager.login(loginParamDTO.getAccount(), loginParamDTO.getPassword());
            return r;
        }
        // 验证码校验不通过, 直接返回
        return this.success(null);
    }
}
